#include "bh1750.h"
#include "delay.h"
#include "init.h"
extern i2c_t *i2c;
/*
    作用：读取设备光照强度
    参数：设备地址
    返回：光照强度
*/
static float bh1750_read_result(u8 addr)
{
    float light = 0;
    char buff[2];
    // start();
    // sendByte(addr | WRITE);
    // waitAck();
    // sendByte(0x01);
    // waitAck();
    // stop();
    i2c->Pi2cStart();
    i2c->Pi2cSendByte(addr | WRITE);
    i2c->Pi2cWaitAck();
    i2c->Pi2cSendByte(0x01);
    i2c->Pi2cWaitAck();
    i2c->Pi2cStop();
    // start();
    // sendByte(addr | WRITE);
    // waitAck();
    // sendByte(0x01);
    // waitAck();
    // stop();
    i2c->Pi2cStart();
    i2c->Pi2cSendByte(addr | WRITE);
    i2c->Pi2cWaitAck();
    i2c->Pi2cSendByte(0x01);
    i2c->Pi2cWaitAck();
    i2c->Pi2cStop();
    // start();
    // sendByte(addr | WRITE);
    // waitAck();
    // sendByte(0x10);
    // waitAck();
    // stop();
    i2c->Pi2cStart();
    i2c->Pi2cSendByte(addr | WRITE);
    i2c->Pi2cWaitAck();
    i2c->Pi2cSendByte(0x10);
    i2c->Pi2cWaitAck();
    i2c->Pi2cStop();
    Delay_ms(200);

    // start();
    // sendByte(addr | READ);
    i2c->Pi2cStart();
    i2c->Pi2cSendByte(addr | READ);
    if ( i2c->Pi2cWaitAck() == 0)
    {
        // sdaIn();
        // buff[0] = recievedByte(1);
        // buff[1] = recievedByte(0);
        // stop();
        i2c->Pi2cSdaIn();
        buff[0] = i2c->Pi2cReciveByte(1);
        buff[1] = i2c->Pi2cReciveByte(0);
        light = ((buff[0] << 8) | buff[1]) / 1.2;
        i2c->Pi2cStop();
    }
    return light;
}
/*
    作用：读取设备光照强度
    参数：设备地址
    返回：光照强度
*/
float deviceGetLight(void)
{
    float result = 0;
    result = bh1750_read_result(0x46);
    return result;
}

bh1750_t *bh1750Create(void)
{
    static bh1750_t bh1750;
    bh1750.PgetLight=deviceGetLight;
	return &bh1750;
}

